<?php

namespace app\admin\controller;

use app\common\BaseHelper;
use app\admin\model\Member as MemberMdl;
use app\admin\model\Membertype;

use think\Exception;
use think\Db;

/**
 * 会员管理
 * @author chenhui
 * @date 2018-06-14
 */
class Member extends Base
{

    public function index(){
        // 获取所有会员分类
        $memberTypeList = $this->getMemberTypeList();
        $this->assign("memberTypeList", $memberTypeList);

        return $this->fetch();
    }

    /**
     * 获取所有会员
     */
    public function getMemberList(){
        $request = $this->request;
        $param = $request->param();

        $start = $param['start'];  // 每页起始条数
        $length = $param['length'];  // 每页显示条数
        $columns = $param['order'][0]['column'];
        $order = $param['columns'][$columns]['data'].' '.$param['order'][0]['dir'];  //排序条件

        $where = [
            'tenantId' => session('TENANT_ID'),
            // 'isMember' => 2
        ];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);
            if($filter['typeId']){
                $where['typeId'] = $filter['typeId'];
            }
            if($filter['mobile']){
                $where['mobile'] = ['like', '%'.$filter['mobile'].'%'];
            }
            if($filter['create_time']){
                list($beginTime, $endTime) = explode(' - ', $filter['create_time']);
                $where['create_time'] = ['between', [strtotime($beginTime), strtotime($endTime) + 24*60*60]];
            }
        }

        $list = MemberMdl::where($where)->limit($start, $length)->order($order)->select();
        foreach ($list as $key => $val) {
            $item = $list[$key];
            $accountdetail = model('Useraccountdetails');
            $accountWhere = [
                'userId' => $item->id,
                'tenantId' => session('TENANT_ID'),
                'rechargeStatus' => 1
            ];
            // 消费次数
            $consumeCount = $accountdetail->where($accountWhere)->count();
            $item->consumeCount = $consumeCount;
            // 消费总额
            $consumeAmount = $accountdetail->where($accountWhere)->sum('money');
            $item->consumeAmount = $consumeAmount / 100;
        }
        $count = MemberMdl::where($where)->count();

        $result = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
        ];

        return json($result);
    }

    /**
     * 获取所有会员分类
     */
    public function getMemberTypeList(){

        $where = [
            //'status' => 1
            'tenantId' => session('TENANT_ID')
        ];
        $typeList = Membertype::where($where)->select();

        return $typeList;
    }

    /**
     * 查看会员
     */
    public function view(){
        $id = $this->request->param('id');
        $where = [
            'a.tenantId' => session('TENANT_ID'),
            'a.id' => $id,
        ];
        /*
        $join = [
            ['__MEMBERTYPE__ t','a.typeId = t.id'],
            ['__USERMEMBERHISTORY__ u','a.id = u.userId'],
        ];
        $fields = 'a.*, t.img as cardImg, u.creatDate as memberTime';
        $info = MemberMdl::alias('a')->where($where)->join($join)->field($fields)->find();
        */
        $info = MemberMdl::alias('a')->where($where)->find();
        //dump($info->memberType);die;
        if(!$info){
            $this->error('该会员不存在！');
        }

        $this->assign("info", $info);

        // 领取优惠券
        $couponCount = db('couponuse')->where(['userId' => $id])->count();
        $this->assign("couponCount", $couponCount);

        return $this->fetch();
    }

    /**
     * 消费记录
     */
    public function getAccountdetailList(){
        $request = $this->request;
        $param = $request->param();
        $model = model('Useraccountdetails');

        $start = $param['start'];  // 每页起始条数
        $length = $param['length'];  // 每页显示条数

        $where = [
            'a.tenantId' => session('TENANT_ID'),
            'a.rechargeStatus' => 1
        ];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);
            if(!$filter['userId']) {
                return json([
                    'status' => '0',
                    'draw' => 0,
                    'data' => [],
                    'recordsFiltered' => 0,
                    'recordsTotal' => 0,
                    'totalNum' => 0,
                ]);
            }else{
                $where['a.userId'] = $filter['userId'];
            }
        }else{
            return json([
                'status' => '0',
                'draw' => 0,
                'data' => [],
                'recordsFiltered' => 0,
                'recordsTotal' => 0,
                'totalNum' => 0,
            ]);
        }
        /*
        $join = [
            ['__ORDER__ o', 'a.orderNO = o.orderNO']
        ];
        $fields = 'a.*, o.total_count, o.userPhone, o.payDate, o.completedtime';
        $list = $model->alias('a')->where($where)->limit($start, $length)->join($join)->field($fields)->select();
        //$list = Db::table('useraccountdetails')->alias('a')->where($where)->limit($start, $length)->join($join)->field($fields)->select();
        */
        $list = $model->alias('a')->where($where)->limit($start, $length)->order('create_time desc')->select();
        $count = $model->alias('a')->where($where)->count();
        $orderModel = db('Order');
        $userModel = db('User');
        foreach ($list as $key => $value) {
            $order = $orderModel->where(['orderNO' => $value->orderNO])->find();
            if($order){
                $value->orderNum = $order['total_count'];
                //$value->money = $order['total'] / 100;
                $value->money = $value->money / 100;
                $value->userPhone = $order['userPhone'];
                //$value->create_time = $order['create_time'];
                //$value->payDate = $order['payDate'];
            }else{
                $user = $userModel->where(['id' => $value->userId])->field('mobile')->find();
                $value->orderNum = 1;
                $value->money = $value->money / 100;
                $value->userPhone = $user['mobile'];
            }
        }

        $allList = $model->alias('a')->where($where)->field('a.userId, a.orderNO, a.money')->select();
        $totalNum = 0;
        foreach ($allList as $k => $v) {
            /*$order = $orderModel->where(['orderNO' => $v->orderNO])->field('orderNO, total')->find();
            if($order){
                $totalNum += $order['total'] / 100;
            }else{
                $totalNum += $v->money / 100;
            }*/
            $totalNum += $v->money;
        }

        $result = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
            'totalNum' => (string)($totalNum / 100),
        ];

        return json($result);
    }

    /**
     * 售后记录
     */
    public function getRefundorderList(){
        $request = $this->request;
        $param = $request->param();
        $model = db('Refundorder');

        $start = $param['start'];  // 每页起始条数
        $length = $param['length'];  // 每页显示条数

        $where = [
            'a.tenantId' => session('TENANT_ID')
        ];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);
            if(!$filter['userId']) {
                return json([
                    'status' => '0',
                    'draw' => 0,
                    'data' => [],
                    'recordsFiltered' => 0,
                    'recordsTotal' => 0,
                    'totalNum' => 0,
                ]);
            }else{
                $where['a.userId'] = $filter['userId'];
            }
        }else{
            return json([
                'status' => '0',
                'draw' => 0,
                'data' => [],
                'recordsFiltered' => 0,
                'recordsTotal' => 0,
                'totalNum' => 0,
            ]);
        }

        $join = [
            ['__PRODUCT__ p', 'a.productId = p.id']
        ];
        $fields = 'a.*, p.imgUrl, p.title';
        $list = $model->alias('a')->where($where)->limit($start, $length)->join($join)->field($fields)->select();
        $count = $model->alias('a')->where($where)->count();
        $totalNum = $model->alias('a')->where($where)->sum('refund_fee');
        $totalNum = $totalNum / 100;

        $result = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
            'totalNum' => (string)$totalNum,
        ];

        return json($result);
    }

    /**
     * 推广收益
     */
    public function getOrdercommissionList(){
        $request = $this->request;
        $param = $request->param();
        $model = db('Ordercommission');

        $start = $param['start'];  // 每页起始条数
        $length = $param['length'];  // 每页显示条数

        $where = [];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);
            if(!$filter['userId']) {
                return json([
                    'status' => '0',
                    'draw' => 0,
                    'data' => [],
                    'recordsFiltered' => 0,
                    'recordsTotal' => 0,
                    'totalNum' => 0,
                    'totalProportion' => 0,
                ]);
            }else{
                //$where['a.userId'] = $filter['userId'];
                $where['a.shangjiId'] = $filter['userId'];
            }
        }else{
            return json([
                'status' => '0',
                'draw' => 0,
                'data' => [],
                'recordsFiltered' => 0,
                'recordsTotal' => 0,
                'totalNum' => 0,
                'totalProportion' => 0,
            ]);
        }

        $join = [
            //['__USER__ u', 'a.userId = u.id'],
            ['__ORDER__ o', 'a.orderId = o.id']
        ];
        //$fields = 'a.*, u.name, o.orderNO';
        $fields = 'a.*, o.userName, o.orderNO';
        $list = $model->alias('a')->where($where)->limit($start, $length)->join($join)->field($fields)->select();
        $count = $model->alias('a')->where($where)->count();
        $totalNum = $totalProportion = 0;
        foreach ($list as $key => &$value) {
            $value['total'] = $value['total'] / 100;
            $value['proportion'] = number_format($value['total'] * $value['proportion'] / 100, 2, '.', '');
            $totalNum += $value['total'];
            $totalProportion += $value['proportion'];
        }

        $result = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
            'totalNum' => (string)number_format($totalNum, 2, '.', ''),
            'totalProportion' => (string)number_format($totalProportion, 2, '.', ''),
        ];

        return json($result);
    }

    /**
     * 提现记录
     */
    public function getUsercommissionList(){
        $request = $this->request;
        $param = $request->param();
        $model = db('Usercommission');

        $start = $param['start'];  // 每页起始条数
        $length = $param['length'];  // 每页显示条数

        $where = [
            'tenantId' => session('TENANT_ID'),
            'status' => 1
        ];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);
            if(!$filter['userId']) {
                return json([
                    'status' => '0',
                    'draw' => 0,
                    'data' => [],
                    'recordsFiltered' => 0,
                    'recordsTotal' => 0,
                    'totalNum' => 0,
                ]);
            }else{
                $where['userId'] = $filter['userId'];
            }
        }else{
            return json([
                'status' => '0',
                'draw' => 0,
                'data' => [],
                'recordsFiltered' => 0,
                'recordsTotal' => 0,
                'totalNum' => 0,
            ]);
        }

        $list = $model->where($where)->limit($start, $length)->select();
        $count = $model->where($where)->count();
        $totalNum = $model->where($where)->sum('amount');
        $totalNum = $totalNum / 100;

        $result = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
            'totalNum' => (string)$totalNum,
        ];

        return json($result);
    }

    /**
     * 下载Excel模板
     */
    public function downloadTemplate(){
        //
        $fileName = ROOT_PATH . 'public' . DS . 'upload' . DS . 'csv' . DS . 'user' . DS . 'template.csv';
    }

    /**
     * 导入数据
     */
    public function import(){
        $file = request()->file('csv_file');

        try {
            $filePath = ROOT_PATH . 'public' . DS . 'upload';
            $info = $file->move($filePath);
            $fileName = $info->getSaveName();
            //$fileName = 'user_' . date('y-m-d-H-i-s') . '.' . substr($file,strripos($file,'.')+1);
            //move_uploaded_file($file, iconv("UTF-8","gb2312", $filePath . DS . $fileName));
            $fileType = \PhpOffice\PhpSpreadsheet\IOFactory::identify($filePath . DS . $fileName);
            $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($fileType);
            // 设置编码
            if(strtolower($fileType) == 'csv'){
                $reader->setInputEncoding('CP936'); // 只对csv文件有效
            }
            $spreadsheet = $reader->load($filePath . DS . $fileName);

            $sheetData = $spreadsheet->getActiveSheet()->toArray();
            if(count($sheetData) <= 1){
                return json(['status' => 0, 'msg' => '未找到文件内容，请填写数据。']);
            }
            foreach ($sheetData as $key => $val) {
                if($key == 0){
                    continue;
                }

                if(count($val) < 26){
                    return json(['status' => 0, 'msg' => '文件内容不正确，请按照模板来填写内容。']);
                }
                $data = [
                    'id'                 => BaseHelper::getUUID22(),
                    'openId'             => $val[1],
                    'name'               => $val[2],
                    'gender'             => in_array($val[3], [1, 2]) ? $val[3] : 1,
                    'dateOfBirth'        => $val[4],
                    'mobile'             => $val[5],
                    'nickName'           => $val[6],
                    'avatarUrl'          => $val[7],
                    'integral'           => intval($val[8]),
                    'create_time'        => strtotime($val[9]),
                    'update_time'        => strtotime($val[10]),
                    'createOper'         => session('member')['id'],//$val[11],
                    'updateOper'         => session('member')['id'],//$val[12],
                    'balance'            => (String)(number_format(floatval($val[13]), 2, '.', '') * 100),
                    'wxCode'             => $val[14],
                    'isMember'           => in_array($val[15], [1, 2]) ? $val[15] : 1,
                    'source'             => in_array($val[16], [1, 2, 3]) ? $val[16] : 3,
                    'status'             => in_array($val[17], [1, 2]) ? $val[17] : 1,
                    'tenantId'           => session("TENANT_ID"),//$val[18], // TODO 商户编号？
                    'qrCode'             => $val[19],
                    'directShareNums'    => intval($val[20]),
                    'directBindNums'     => intval($val[21]),
                    'chiefUserId'        => $val[22], // TODO 分销上级是否存在呢？
                    'directShareQunNums' => intval($val[23]),
                    'totalIncome'        => (String)(number_format(floatval($val[24]), 2, '.', '') * 100),
                    'totalWithdrawals'   => (String)(number_format(floatval($val[25]), 2, '.', '') * 100),
                    'qrCode1'            => isset($val[26]) ? $val[26] : '',
                ];
                MemberMdl::insert($data);
            }
            @unlink($filePath . DS . $fileName);
            //$this->success('导入成功！', url('admin/member/index'));
            return json(['status' => 1, 'msg' => '导入成功！']);
        } catch (\Exception $e){
            //$msg = $e->getMessage();
            $msg = '导入失败，请严格按照模板来填写内容。';
            //$this->error($msg, url('admin/member/index'));
            return json(['status' => 0, 'msg' => $msg]);
        }

        return json(['status' => 0, 'msg' => $msg]);
    }

    /**
     * 导出数据
     */
    public function export(){
        $param = $this->request->param();

        $where = [
            'tenantId' => session('TENANT_ID'),
            'isMember' => 2
        ];
        if(!empty($param['typeId'])){
            $where['typeId'] = $param['typeId'];
        }
        if(!empty($param['mobile'])){
            $where['mobile'] = ['like', '%'.$param['mobile'].'%'];
        }
        if(!empty($param['create_time'])){
            list($beginTime, $endTime) = explode(' - ', $param['create_time']);
            $where['create_time'] = ['between', [strtotime($beginTime), strtotime($endTime) + 24*60*60]];
        }

        //$data = MemberMdl::where($where)->order('create_time', 'asc')->limit(1000)->select();
        $data = MemberMdl::where($where)->order('create_time', 'asc')->select();
        if(count($data) <= 0){
            $this->error('没有数据！', url('admin/member/index'));
        }
        foreach ($data as $key => $val) {
            // 性别
            switch ($val['gender']) {
                case 1: $val['gender'] = '男'; break;
                case 2: $val['gender'] = '女'; break;
                default : $val['gender'] = '男'; break;
            }
            // 佣金
            $val['balance'] = $val['balance'] / 100 . ' 元';
            // 是否会员
            switch ($val['isMember']) {
                case 1: $val['isMember'] = '不是'; break;
                case 2: $val['isMember'] = '是'; break;
                default : $val['isMember'] = '不是'; break;
            }
            // 用户来源
            switch ($val['source']) {
                case 1: $val['source'] = '外部导入'; break;
                case 2: $val['source'] = '内部添加'; break;
                case 3: $val['source'] = '小程序下单'; break;
                default : $val['source'] = '小程序下单'; break;
            }
            // 状态
            switch ($val['status']) {
                case 1: $val['status'] = '正常'; break;
                case 2: $val['status'] = '非法'; break;
                default : $val['status'] = '正常'; break;
            }
            // 总收益
            $val['totalIncome'] = $val['totalIncome'] / 100 . ' 元';
            // 总提现
            $val['totalWithdrawals'] = $val['totalWithdrawals'] / 100 . ' 元';
        }
        $cellName = array(
            'A' => ['id', '用户编号'],
            'B' => ['openId', '微信标识'],
            'C' => ['name', '姓名'],
            'D' => ['gender', '性别'],
            'E' => ['dateOfBirth', '生日'],
            'F' => ['mobile', '手机'],
            'G' => ['nickName', '微信昵称'],
            'H' => ['avatarUrl', '头像'],
            'I' => ['integral', '积分'],
            'J' => ['create_time', '创建时间'],
            'K' => ['update_time', '修改时间'],
            'L' => ['createOper', '创建人'],
            'M' => ['updateOper', '修改人'],
            'N' => ['balance', '余额'],
            'O' => ['wxCode', '微信号'],
            'P' => ['isMember', '是否会员'],
            'Q' => ['source', '用户来源'],
            'R' => ['status', '状态'],
            'S' => ['tenantId', '商户编号'],
            'T' => ['qrCode', '分销二维码'],
            'U' => ['directShareNums', '分享次数'],
            'V' => ['directBindNums', '分享成功次数'],
            'W' => ['chiefUserId', '分销上级编号'],
            'X' => ['directShareQunNums', '分享群次数'],
            'Y' => ['totalIncome', '总收益'],
            'Z' => ['totalWithdrawals', '总提现'],
            'AA' => ['qrCode1', '分销小程序码'],
        );

        $filePath = ROOT_PATH . 'public' . DS . 'upload' . DS . 'csv' . DS . 'user' . DS . date('Y-m-d');
        $fileName = $filePath . '/user_' . date('y-m-d-H-i-s');

        $excel = new Excel();
        $excel->exportExcel('会员', $data, $cellName, $filePath, $fileName);

        return redirect('admin/member/index');
    }

}